package org.parademo.service.security;

import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {
    public static ParademoUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            return null;
        }

        Object principal = authentication.getPrincipal();

        if (isAnonymous(authentication)) {
            return null;
        }

        if (principal instanceof ParademoUser) {
            return (ParademoUser) principal;
        } else {
            return null;
        }
    }

    public static String getCurrentUserName() {
        ParademoUser currentUser = getCurrentUser();

        if (currentUser == null) {
            return null;
        }

        return currentUser.getUsername();
    }

    private static boolean isAnonymous(Authentication authentication) {
        AuthenticationTrustResolverImpl authenticationTrustResolver = new AuthenticationTrustResolverImpl();

        return authenticationTrustResolver.isAnonymous(authentication);
    }
}
